package com.business.sys.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.business.sys.entity.Area;
import com.business.sys.mapper.AreaMapper;
import com.business.sys.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


/**
 * 区域表:业务接口实现类
 *
 * @author chenjiehong
 * @date 2019-04-28 15:03:17
 * @since 1.0
 */
@Service
public class AreaServiceImpl implements AreaService {

    @Autowired
    private AreaMapper sysAreaMapper;

    @Override
    @Transactional(readOnly = true)
    public List<Area> queryAllCity() {
        Wrapper<Area> wrapper = new EntityWrapper<>();
        wrapper.eq("state", 1).eq("type", 2).orderBy("first_pinyin");
        List<Area> list = sysAreaMapper.selectList(wrapper);
        String previouPY = null;//上一个遍历的拼音
        for (int i = 0; i < list.size(); i++) {
            Area area = list.get(i);
            if (area.getFirstPinyin() == null) {
                continue;
            }
            String py = area.getFirstPinyin().substring(0, 1);
            if (!py.equals(previouPY) || previouPY == null) {
                Area letterArea = new Area();
                String letter = py.toUpperCase();
                letterArea.setName(letter);
                letterArea.setPinyin(letter);
                letterArea.setFirstPinyin(letter);
                list.add(i, letterArea);
                i++;
            }
            previouPY = py;
        }
        return list;
    }

    @Override
    @Transactional(readOnly = true)
    public List<Area> query(Integer parentId) {
        Area sysArea = new Area();
        sysArea.setParentId(parentId);
        sysArea.setState(1);
        EntityWrapper<Area> wrapper = new EntityWrapper<>(sysArea);
        return sysAreaMapper.selectList(wrapper);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> queryAll() {
        return getSublist(0);
    }

    /**
     * 获取子列表
     *
     * @param parentId
     * @return
     */
    private List<Map<String, Object>> getSublist(int parentId) {
        Wrapper<Area> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("id,code,name,type").eq("state", 1).eq("parent_id", parentId);
        List<Map<String, Object>> sublist = sysAreaMapper.selectMaps(wrapper);
        if (sublist == null || sublist.size() == 0) {
            return null;
        }
        for (Map<String, Object> m : sublist) {
            Integer type = Integer.parseInt(m.get("type") + "");
            if (type < 2) {
                Integer id = Integer.parseInt(m.get("id") + "");
                m.put("sublist", getSublist(id));
            }
        }
        return sublist;
    }
}